package com.cloudm.technician.ui.modules.cloudm_box.debug_result

import com.cloudm.technician.data.network.CloudmBoxApi
import com.cloudm.technician.ui.base.RxPresenter
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.util.concurrent.TimeUnit

/**
 * 作者: wesley
 * 时间: 2017/12/21
 * 描述: 业务逻辑
 */
class DebugResultPresenter(private val view: DebugResultContract.View,
                           private val cloudmBoxApi: CloudmBoxApi) : RxPresenter(),
        DebugResultContract.Presenter {


    override fun getDebugResultInfo(id: Int, sn: String, lng: Double, lat: Double,
                                    recordId: String?) {
        debugging()
        request(cloudmBoxApi.getDebugResultInfo(id, sn, lat, lng, recordId), view,
                onSuccess = { info, _ ->
                    when (info) {
                        null -> {
                            view.showDebugInfoEmpMsg()
                            debugNoPass()
                        }
                        else -> {
                            view.loadSuccess(info)
                            when (info.isPass) {
                                1 -> debugPass()
                                2 -> debugNoPass()
                            }
                        }
                    }
                }, onFailure = { errorMsg ->
            view.loadFailure(errorMsg)
            debugNoPass()
            view.finishSelf()
        })
    }


    override fun openActivityOrDebug(tag: String, id: Int, sn: String, lng: Double, lat: Double,
                                     recordId: String?) {
        when (tag) {
            "0" -> getDebugResultInfo(id, sn, lng, lat, recordId)
            "1" -> view.openUploadPicActivity()
        }
    }


    override fun onLocationClick(tag: String) {
        when (tag) {
            "0" -> view.showLocationEmpMsg()
            "1" -> view.openMapPreviewActivity()
        }
    }


    private fun debugging() {
        view.setBtnNotEnabled()
        view.setBtnTextDebug()
    }


    private fun debugNoPass() {
        view.setBtnEnabled()
        view.setBtnTextNotPass()
    }


    private fun debugPass() {
        view.setBtnEnabled()
        view.setBtnTextNext()
    }


    override fun countDown() {
        Observable.timer(3, TimeUnit.SECONDS).subscribeOn(Schedulers.io()).observeOn(
                AndroidSchedulers.mainThread()).filter { view.isActive }.subscribe({
            if (!view.isLocationLoaded()) {
                view.reloadLocation()
            }
        })
    }
}